package com.morn.fanfou.widget;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.morn.fanfou.R;
import com.morn.fanfou.model.Message;
import com.morn.fanfou.util.DateUtil;

public class ConversationAdapter extends BaseAdapter {

	private List<Message> list;
	private LayoutInflater inflater;
	private static int resource = R.layout.conversation_item;
	private String otherId;

	public ConversationAdapter(Context context, List<Message> list,
			String otherId) {
		this.otherId = otherId;
		this.list = list;
		this.list = list;
		this.inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Message message = list.get(position);
		View vi = convertView;
		ViewHolder holder;
		if (convertView == null) {
			vi = inflater.inflate(resource, null);
			holder = new ViewHolder();
			holder.bgView = (LinearLayout) vi
					.findViewById(R.id.conversation_item_bgView);
			holder.msgInfo = (TextView) vi
					.findViewById(R.id.conversation_item_msgInfo);
			holder.timeInfo = (TextView) vi
					.findViewById(R.id.conversation_item_timeInfo);
			vi.setTag(holder);
		} else
			holder = (ViewHolder) vi.getTag();

		holder.timeInfo.setText(DateUtil.formatDate(message.getCreated_at(),
				"yyyy-MM-dd HH:MM:ss"));
		holder.msgInfo.setText(message.getText());

		String recipientId = message.getRecipient_id();
		LayoutParams params = new LayoutParams(holder.bgView.getLayoutParams());
		params.addRule((otherId.equals(recipientId)) ? RelativeLayout.ALIGN_PARENT_RIGHT
				: RelativeLayout.ALIGN_PARENT_LEFT);
		holder.bgView.setLayoutParams(params);

		return vi;
	}

	public static class ViewHolder {
		public LinearLayout bgView;
		public TextView msgInfo;
		public TextView timeInfo;
	}

}
